import React, { useState } from "react";
import { Table, Form, Button, Row, Col, Collapse, Input, Select, DatePicker } from "antd";
import type { FormProps, InputProps } from "antd";
import { SearchOutlined, PlusOutlined, DownOutlined } from "@ant-design/icons";
import type { TableProps } from "antd";
import type { ColumnsType } from "antd/es/table";
import type { FormInstance, FormItemProps } from "antd/es/form";
import type { PaginationResult } from "@/types/api";

const { Panel } = Collapse;
const { Option } = Select;
const { RangePicker } = DatePicker;

// 表单字段配置接口
export interface FilterFieldConfig {
  type: "Input" | "Select" | "Date" | "DateRange";
  formItemProps?: FormItemProps;
  componentProps?: any;
  [key: string]: any;
}
// 表单配置接口
export interface FormConfig {
  // Form组件属性
  formProps?: FormProps;
  // 基础筛选字段配置
  basicFields?: FilterFieldConfig[];
  // 高级筛选字段配置
  advancedFields?: FilterFieldConfig[];
}
export interface FilterTableProps<T> {
  // 表格数据
  dataSource: T[];
  // 表格列配置
  columns: ColumnsType<T>;
  // 加载状态
  loading: boolean;
  // 分页配置
  pagination: {
    current: number;
    pageSize: number;
    total: number;
    onChange: (page: number, pageSize: number) => void;
    onShowSizeChange?: (current: number, pageSize: number) => void;
  };
  // 搜索筛选表单配置（原有方式）
  filters?: React.ReactNode;
  // 高级筛选表单配置（原有方式）
  advancedFilters?: React.ReactNode;
  // 查询按钮点击事件
  onSearch: () => void;
  // 重置按钮点击事件
  onReset?: () => void;
  // 批量操作按钮配置
  batchActions?: React.ReactNode;
  // 表格操作按钮配置
  tableActions?: React.ReactNode;
  // 是否显示高级筛选
  showAdvancedFilter?: boolean;
  // 表单配置（新增，用于内置表单）
  formConfig?: FormConfig;
}
// 2. 定义更明确的componentMap类型
interface ComponentMap {
  [key: string]: React.ComponentType<any>;
}
const componentMap: ComponentMap = {
  Input,
  Select,
  Date: DatePicker,
  DateRange: RangePicker,
};

/**
 * 带筛选项的表格组件
 * 包含基本筛选、高级筛选、折叠展开、表格操作等功能
 */
const FilterTable = <T,>({
  dataSource,
  columns,
  loading = false,
  pagination,
  filters,
  advancedFilters,
  onSearch,
  onReset,
  batchActions,
  tableActions,
  showAdvancedFilter = true,
  formConfig,
}: FilterTableProps<T>) => {
  // 高级筛选展开状态
  const [advancedVisible, setAdvancedVisible] = useState(true);
  // 创建表单实例（新增）
  const [form] = Form.useForm();

  // 切换高级筛选显示状态
  const toggleAdvancedFilter = () => {
    setAdvancedVisible((prev) => !prev);
  };
  const handleSubmit = () => {
    if (formConfig?.formProps?.onFinish) {
      form
        .validateFields()
        .then((values) => {
          if (formConfig.formProps?.onFinish) {
            formConfig.formProps.onFinish(values);
          }
        })
        .catch();
    }
  };
  // 重置筛选条件
  const handleReset = () => {
    form.resetFields();
    handleSubmit();
    setAdvancedVisible(false);
  };
  return (
    <div className="filter-table-container" style={{ width: "100%", height: "100%" }}>
      {/* 筛选区域 */}
      <div
        className="filter-section"
        style={{
          marginBottom: 16,
          padding: 16,
          backgroundColor: "#f5f5f5",
          borderRadius: 6,
        }}
      >
        {/* 使用内置表单配置 */}
        {formConfig && (
          <>
            <Form
              form={form}
              layout="inline"
              className="s-form"
              style={{ display: "flex", gap: "10px" }}
              {...(formConfig?.formProps || {})}
            >
              {formConfig.basicFields &&
                formConfig.basicFields.map((item, index) => (
                  <Form.Item
                    key={index}
                    style={{ width: "20%", margin: 0 }}
                    {...item.formItemProps}
                  >
                    {componentMap[item.type] &&
                      React.createElement(componentMap[item.type] as React.ComponentType, {
                        ...item.componentProps,
                      })}
                  </Form.Item>
                ))}
              {showAdvancedFilter &&
                formConfig.advancedFields &&
                advancedVisible &&
                formConfig.advancedFields.map((item, index) => (
                  <Form.Item
                    key={index}
                    style={{ width: "20%", margin: 0 }}
                    {...item.formItemProps}
                  >
                    {componentMap[item.type] &&
                      React.createElement(componentMap[item.type] as React.ComponentType, {
                        ...item.componentProps,
                      })}
                  </Form.Item>
                ))}
            </Form>
            {/* 操作按钮区域 */}
            <div
              className="filter-actions"
              style={{
                marginTop: 16,
                display: "flex",
                justifyContent: "flex-end",
                gap: 8,
              }}
            >
              {showAdvancedFilter &&
                (!formConfig?.advancedFields || formConfig.advancedFields.length > 0) && (
                  <Button
                    type="link"
                    icon={<DownOutlined rotate={advancedVisible ? 180 : 0} />}
                    onClick={toggleAdvancedFilter}
                  >
                    {advancedVisible ? "收起" : "展开"}高级筛选
                  </Button>
                )}

              <Button type="primary" icon={<SearchOutlined />} htmlType="submit">
                查询
              </Button>
              <Button onClick={handleReset}>重置</Button>
            </div>
          </>
        )}
      </div>

      {/* 表格上方操作区域 */}
      {(batchActions || tableActions) && (
        <div
          className="table-header-actions"
          style={{
            marginBottom: 16,
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
          }}
        >
          <div>{batchActions}</div>
          <div>{tableActions}</div>
        </div>
      )}

      {/* 表格组件 */}
      <Table
        dataSource={dataSource}
        columns={columns}
        rowKey={(record: any) => record.id || record.key}
        pagination={pagination}
        loading={loading}
        size="middle"
        scroll={{ x: "max-content" }}
        className="custom-table"
      />
    </div>
  );
};

export default FilterTable;
